import helper from '@/common/helper.js';
import { mapState } from 'vuex';
import {exchangeFile ,compressImage} from '@/common/compress.js';
export default {
	data() {
		return {
			img_change : 0,
			show:false,
			content : '提交成功,稍后可查看报告',
			is_ocr : 0,
			m2 : 2097152, 
		
		}
	},
	computed: {
       ...mapState(['hasLogin', 'userInfo']),
	},
	methods: {	
		model_act(){
			this.show = !this.show; 
		},
		model_com(){
			this.show = !this.show; 
			setTimeout(()=>{
				//this.$r('/pages/index/index','rel');
			},800)
		},
		//行驶证识别
		check_ocr(base64){
			if(this.hasLogin){      
				let url = this.site_url + 'api/auth/index/check_api_ocr';	 
				let param = {base64_img : base64};
				this.areq(url,param,'POST').then(res=>{
					 if(res.code == 1){
						 this.car_num = res.data.PlateNo;
						 this.vtype = res.data.VType;
						 this.reg_time = res.data.RegisterDate;
						 this.owner = res.data.Owner;
						 this.vinstr = res.data.VIN; 
						 this.car_model = res.data.Model;
						 this.is_ocr = 1;
						 if(res.data.car_info.code ==200){
							 this.has_info = 1;
							 this.car_info = res.data.car_info.data;
						 }
						 
					 }else{
						 this.showMsg(res.msg)
					 }
				}) 
			}else{
				this.content = '登录才可调用行驶证识别功能。';
				this.model_act();
			}
		},
        checkVIN(VIN){
        	    if(typeof(VIN)!='string') return false;
        	    if(VIN.length!=17) return false;
        	    VIN=VIN.toUpperCase();
        	    let RE= /^[A-HJ-NPR-Z\d]{8}[X\d][A-HJ-NPR-Z\d]{3}\d{5}$/
        	    if(!RE.test(VIN)) return false;
        	    let cOT={
        	        '0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,
        	        '8':8,'9':9,'A':1,'B':2,'C':3,'D':4,'E':5,'F':6,
        	        'G':7,'H':8,'J':1,'K':2,'L':3,'M':4,'N':5,'P':7,
        	        'R':9,'S':2,'T':3,'U':4,'V':5,'W':6,'X':7,'Y':8,
        	        'Z':9
        	    };
        	    let xWT= [8,7,6,5,4,3,2,10,0,9,8,7,6,5,4,3,2]; // 因为第9位权重为0，所以原来是什么字符不影响结果，可以方便后面计算
        	    let sum= 0;
        	    let VINs= VIN.split('');
        	    for(let i=0;i<17;i++){
        	        sum=sum + cOT[ VINs[i] ] * xWT[i];
        	    }
        	    let cT=['0','1','2','3','4','5','6','7','8','9','X'];
        	    if( cT[ (sum%11) ] == VINs[8]) return true;
        	    return false;
        	},
        	confirm_order() {
        		// if(!this.agree){
        		// 	this.showMsg('请勾选用户协议');
        		// 	return false;
        		// }
				
				if(this.userInfo.is_sm != 2){
					uni.showModal({
						title: '认证提示',
						content: '请先实名认证,点确定跳转',
						success:  res  => {
							if (res.confirm) {
								 this.$r('/pages/personalcenter/standing');
							} else if (res.cancel) {
								//console.log('用户点击取消');
							}
						}
					});
					return false;
				}
				
				
        		if(this.fileList6.length == 0){
        			this.showMsg('请上传行驶证图片');
        			return false;
        		}
        		let m5 = 5242880;
        		if(this.fileList6[0].size > m5){
        		  this.showMsg('图片大小不能超过5MB',2500);
        		  return false;
        		}
        		if (this.vinstr == '') {
        			this.showMsg('请输入车架号');
        			return false;
        		}
        		if(this.checkVIN(this.vinstr) == false){
        			this.showMsg('车架号格式有误,请检查');
        			return false;
        		}
        		uni.$u.throttle(this.real_confirm_order, 2000)
        	},
			real_confirm_order() {
				uni.showLoading({
					title: '请稍后'
				});
				let base64 = this.fileList6[0].url;
				helper.Timer.start();
				this.req({
					url: this.site_url + 'api/index/create_car_order?stype='+this.stype,
					method: 'POST',
					data: {
						img_data: base64,
						vin: this.vinstr,
						stype : this.stype
					},
					success: res => {
						let ret = res.data;
						if (ret.code == 1) {
							// this.showMsg('提交成功');
							helper.Timer.stop();
							let left_time = helper.Timer.getLeftTime(2000);
							setTimeout(() => {
								uni.hideLoading();
								// uni.$emit('auto_login');
								this.order = ret.data;
								this.content = '提交成功,稍后可查看报告';
								setTimeout(()=>{
									this.model_act();
								},1200);
							}, left_time);
							
						} else {
							uni.hideLoading();
							this.showMsg(ret.msg);
						}
					},
					fail: err => {
						uni.hideLoading();
						this.showMsg('网络错误');
					}
				});
			},
        	real_confirm_order_ori() {
        		uni.showLoading({
        			title: '请稍后'
        		});
        		let base64 = this.fileList6[0].url;
        		helper.Timer.start();
        		this.req({
        			url: this.site_url + 'api/index/create_car_order?stype='+this.stype,
        			method: 'POST',
        			data: {
        				img_data: base64,
        				vin: this.vinstr,
        				stype : this.stype
        			},
        			success: res => {
        				let ret = res.data;
        				if (ret.code == 1) {
        					// this.showMsg('提交成功');
        					helper.Timer.stop();
        					let left_time = helper.Timer.getLeftTime(2000);
        					setTimeout(() => {
        						uni.hideLoading();
        						// uni.$emit('auto_login');
        						this.order = ret.data;
        						this.real_confirm();
        					}, left_time);
        					
        				} else {
        					uni.hideLoading();
        					this.showMsg(ret.msg);
        				}
        			},
        			fail: err => {
        				uni.hideLoading();
        				this.showMsg('网络错误');
        			}
        		});
        	},
        	async real_confirm() {
        		let that = this;
        		this.req({
        			url: this.site_url + 'api/auth/order/car_pay',
        			method: 'POST',
        			data: {
        				order_id: this.order.id,
        				money: this.order.pay_price,
        				plat: 'miniapp'
        			},
        			success: res => {
        				let ret = res.data;
        				if (ret.code == 1) {
        					uni.requestPayment({
        						provider: 'wxpay',
        						timeStamp: ret.data.timeStamp.toString(),
        						nonceStr: ret.data.nonceStr,
        						package: ret.data.package,
        						signType: ret.data.signType,
        						paySign: ret.data.paySign,
        						success(res) {
        							this.content = '提交成功,稍后可查看报告';
        							this.model_act();
        						},
        						fail(err) {
        							that.showMsg('支付取消');
        						}
        					});
        				} else {
        					that.showMsg(ret.msg, 2000);
        
        				}
        			},
        			fail: err => {
        				this.showMsg('网络错误');
        			}
        		});
        	},
        	agreeChange(_flag) {
        		this.agree = _flag;
        	},
        	// 删除图片
        	deletePic(event) {
        		this[`fileList${event.name}`].splice(event.index, 1)
        	},
        	// 新增图片
        	async afterRead(event) {
        		// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
        		let lists = [].concat(event.file);
				
        		let fileListLen = this[`fileList${event.name}`].length;
        		lists.map((item) => {
        			this[`fileList${event.name}`].push({
        				...item,
        				status: 'uploading',
        				message: '上传中'
        			})
        		})
				  let finallPath;
        		for (let i = 0; i < lists.length; i++) {
					
        			if( lists[i].size < this.m2){
        				 finallPath = await exchangeFile(lists[i].url)
        			}else{
        			   //图片大于2M，走压缩
        				 finallPath = await compressImage.call(this, lists[i].url); // 压缩图片
        			}	
					
        			 let result = await this.urlTobase64(finallPath);
					 if(event.name == 6){
						 this.check_ocr(result);
					 }
					
        			let item = this[`fileList${event.name}`][fileListLen]
					this.img_change = 1;
        			this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
        				status: 'success',
        				message: '',
        				url: result
        			}))
        			fileListLen++
        		}
        	},
        	urlTobase64(url) {
        		var promise = new Promise((resolve, reject) => {
        		// #ifdef MP-WEIXIN
        		uni.getFileSystemManager().readFile({
        			filePath: url, //选择图片返回的相对路径
        			encoding: 'base64', //编码格式
        			success: res => { //成功的回调
        				//console.log(res);
        				let base64 = 'data:image/jpeg;base64,' + res.data //不加上这串字符，在页面无法显示的哦
        				resolve(base64);
        			},
        			fail: (e) => {
        				console.log("图片转换失败");
        				reject(0);
        			}
        		})
        		// #endif
        		// #ifndef MP-WEIXIN
        		uni.request({
        			url: url,
        			method: 'GET',
        			responseType: 'arraybuffer',
        			success: ress => {
        				let base64 = wx.arrayBufferToBase64(ress.data); //把arraybuffer转成base64 
        			//	console.log(base64)
        				base64 = 'data:image/jpeg;base64,' + base64 //不加上这串字符，在页面无法显示的哦
        				resolve(base64);
        			},
        			fail: (e) => {
        				console.log("图片转换失败");
        				reject(0);
        			}
        		})
        		// #endif
        		});
        		return promise;
        	}
        

	}

}
